package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.service.GoodsService;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author fenge
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;

    @Override
    public Map<String,Object> listInventory(Integer page, Integer rows, String codeOrName, Integer goodsTypeId) {

        Integer offset = (page-1) * (rows);
        List<Goods> goodsList = goodsDao.listInventory(offset,rows,codeOrName,goodsTypeId);
        Long total = goodsDao.getTotal();
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",goodsList);
        return map;
    }

    @Override
    public void save(Goods goods) {
        if (goods.getGoodsId()==null){
            goods.setGoodsCode(String.format("%04d",goodsDao.getTotal()+1));
            goodsDao.save(goods);
        } else {
            goodsDao.update(goods);
        }
    }

    @Override
    public void delete(Integer goodsId) {
        Goods goods = goodsDao.getById(goodsId);
        if (goods.getState()==0){
            goodsDao.deleteById(goodsId);
        }
    }

    @Override
    public Map<String, Object> getNoInventoryQuantity(Integer page, Integer rows, String nameOrCode) {
        Integer offset = (page-1) * (rows);
        List<Goods> goodsList = goodsDao.getTotalOfNo(offset,rows,nameOrCode);
        Integer countNoInventoryQuantity = goodsDao.countNoInventoryQuantity(nameOrCode);
        Map<String, Object> map = new HashMap<>();
        map.put("total",countNoInventoryQuantity);
        map.put("rows",goodsList);

        return map;
    }

    @Override
    public Map<String, Object> getHasInventoryQuantity(Integer page, Integer rows, String nameOrCode) {
        Integer offset = (page-1) * (rows);
        List<Goods> goodsList = goodsDao.getHasInventoryQuantity(offset,rows,nameOrCode);
        Map<String, Object> map = new HashMap<>();
        Integer countHasInventoryQuantity = goodsDao.countHasInventoryQuantity(nameOrCode);
        map.put("total",countHasInventoryQuantity);
        map.put("rows",goodsList);

        return map;
    }

    @Override
    public void saveStock(Integer goodsId, Integer inventoryQuantity, double purchasingPrice) {
        Goods goods = goodsDao.getById(goodsId);
        goods.setInventoryQuantity(inventoryQuantity);
        goods.setPurchasingPrice(purchasingPrice);
        goodsDao.update(goods);
    }

    @Override
    public Map<String, Object> listAlarm() {
        List<Goods> goods = goodsDao.listAlarm();
        Map<String, Object> map = new HashMap<>();
        map.put("rows",goods);
        return map;
    }
}
